using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Elmah;
using SubSonic;
using SurveyHost.Core.DAL;
using System.Net.Mail;
using SurveyHost.Core;
using System.Text;

namespace SurveyHost.Web.Participant
{
    public partial class SurveyComplete : System.Web.UI.Page
    {

        #region  Properties and variables (5)

        private string _name = null;
        private string _userId = null;
        /// <summary>
        /// Gets the checksum for a user.
        /// </summary>
        /// <remarks>Okay, its not really a checksum.  Its a simple hash.  But its reproducible.</remarks>
        /// <value>The checksum.</value>
        public string Checksum
        {
            get
            {
                return Math.Abs(UserId.GetHashCode()).ToString();
            }
        }

        /// <summary>
        /// Gets the name of the given.
        /// </summary>
        /// <value>The name of the given.</value>
        public string GivenName
        {
            get
            {
                if (User.IsInRole("Admin")) // admins cannot take their own surveys; need to do this so the admin can view the page
                    return "Administrator";
                if (_name == null)
                {
                    _name = ActiveRecord<UserStatus>.FetchByID(WebUtil.CurrentUserId()).EnteredName;
                }
                return _name;
            }
        }

        /// <summary>
        /// Gets the user id.
        /// </summary>
        /// <value>The user id.</value>
        public string UserId
        {
            get
            {
                if (_userId == null)
                    _userId = WebUtil.CurrentUserId().ToString();
                return _userId;
            }
        }

        #endregion

        #region  Methods (2)

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if(User.IsInRole("Admin"))
            {
                Send.Enabled = false;
                emailAddy.ReadOnly = true;
                return;
            }
            Guid id = WebUtil.CurrentUserId();
            // bail if the user didn't consent
            if (StatusHelper.IsCompleted(id) && !StatusHelper.UserIsValid(id))
                Response.Redirect("NonParticipating.aspx", true);
            // user has complted validation but does not meet requirements, just let them through
            if (StatusHelper.UserHasCompletedValidation(id) &&
                !StatusHelper.UserIsValid(id))
                return;
            // user has complted validation, meets requirements, but has not completed the survey
            if (!StatusHelper.IsCompleted(id))
                Response.Redirect("Survey.aspx", true);

        }

        /// <summary>
        /// Handles the Click event of the Send control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Send_Click(object sender, EventArgs e)
        {
            if (User.IsInRole("Admin")) return;
            if (string.IsNullOrEmpty(emailAddy.Text)) return;

            bool success = true;
            try
            {
                MembershipUser user = Membership.GetUser(WebUtil.CurrentUserId());
                WebUtil.SendCompletionEmail(
                    Request.Url.Scheme + "://" + Request.Url.Authority + '/', // goddamnit.
                    emailAddy.Text,
                    SurveyManager.SessionInstance.CurrentSurvey.EndTime.Value.ToString("f"),
                    GivenName,
                    user.Email,
                    user.UserName,
                    Checksum
                    );
            }
            catch (ArgumentNullException ane)
            {
                ErrorSignal.FromCurrentContext().Raise(ane);
                success = false;
            }
            catch (ArgumentOutOfRangeException aoore)
            {
                ErrorSignal.FromCurrentContext().Raise(aoore);
                success = false;
            }
            catch (InvalidOperationException ioe)
            {
                ErrorSignal.FromCurrentContext().Raise(ioe);
                success = false;
            }
            catch (SmtpException se)
            {
                ErrorSignal.FromCurrentContext().Raise(se);
                success = false;
            }
            catch (NullReferenceException nre)
            {
                ErrorSignal.FromCurrentContext().Raise(nre);
                success = false;
            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(
                    new InvalidOperationException(
                        "Unable to send confirmation emails.", ex));
                success = false;
            }
            Status.Text = success
              ? "Email sent!"
              : "Email could not be sent.  An administrator has been notified.  Please save your confirmation number!";
            Status.Visible = true;
            Send.Enabled = false;
        }

        #endregion

    }
}
//e b i c   
//h a n 1